package dkbta.ontology.loading;

import java.util.LinkedHashMap;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import dkbta.ontology.Ontology;
import dkbta.ontology.elements.ElementType;
import dkbta.ontology.elements.event.EventDef;
import dkbta.ontology.loading.OntologyParser.ElementParser;
import dkbta.ontology.values.ScaledValues;
import dkbta.util.Utils;

final class EventParser implements ElementParser{

	private final Ontology _ontology;

	public EventParser(Ontology ontology){
		_ontology = ontology;
	}

	@Override
	public ElementType getElementType(){
		return ElementType.EVENT;
	}

	public void parseElement(Element event, String name, String componentType)
			throws OntologyException{
		Element attributesElement = OntologyParser.getXmlElement(event, "Attributes");
		LinkedHashMap<String, ScaledValues> attributes = new LinkedHashMap<String, ScaledValues>();
		if (attributesElement != null){
			// Parsing each of the attributes
			NodeList attributeElements = attributesElement
					.getElementsByTagName("Attribute");
			int length = attributeElements.getLength();
			attributes = new LinkedHashMap<String, ScaledValues>(length);
			for (int i = 0; i < length; ++i){
				parseEventAttribute((Element)attributeElements.item(i), attributes);
			}
		}else{
			attributes = new LinkedHashMap<String, ScaledValues>(0);

		}
		_ontology.addEvent(new EventDef(name, componentType, attributes));
	}

	private void parseEventAttribute(Element attribute,
		LinkedHashMap<String, ScaledValues> attributes) throws OntologyException{
		String name = attribute.getAttribute("name");
		if (Utils.isEmpty(name)){
			throw new OntologyException("Attribute without a valid name");
		}

		try{
			ScaledValues sv = OntologyParser.parseScaledValues(attribute);
			if (sv == null){
				throw new OntologyException("Attribute " + name + " has no valid values");
			}else{
				attributes.put(name, sv);
			}
		}catch(OntologyException e){
			throw new OntologyException("Attribute " + name + " has no valid values", e);
		}
	}
}